package com.springboot.admin.security.config;

import com.springboot.admin.jwt.JwtTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    JwtTokenFilter jwtTokenFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.addFilterBefore(jwtTokenFilter, UsernamePasswordAuthenticationFilter.class)
                // 禁用session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER)
                .and()
                .authorizeRequests()
                // 放行登录请求
                .antMatchers("/account/login").permitAll()
                // 放行退出请求
                .antMatchers("/account/logout").permitAll()
                // 放行注册请求
                .antMatchers("/account/register").permitAll()
                // 放行所有get请求
                .antMatchers("/**/get*/**").permitAll()
                // 放行测试接口
                .antMatchers("/test**/**").permitAll()
                // 放行swagger3相关资源
                // 访问地址：http://localhost:8091/bootService/swagger-ui/index.html
                .antMatchers("/swagger-ui/**").permitAll()
                .antMatchers("/webjars/**").permitAll()
                .antMatchers("/v3/**").permitAll()
                .antMatchers("/swagger-resources/**").permitAll()
                // 放行静态文件
                .antMatchers("/**/**.html").permitAll()

                // 其他请求都要求认证
                .anyRequest().authenticated()
                .and()
                // 将推出接口映射到controller接口
                .logout().logoutUrl("/bootService/account/logout")
                .and()
                // 允许跨域
                .csrf().disable();
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }


}
